<template>
  <el-card class="quick-actions-panel">
    <template #header>
      <div class="panel-header">
        <span>快速操作</span>
        <el-button link size="small" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </template>

    <div v-loading="loading" class="actions-grid">
      <!-- 统计卡片 -->
      <div class="stats-section">
        <el-row :gutter="12">
          <el-col v-for="stat in quickStats" :key="stat.key" :span="6">
            <div
              class="stat-card"
              :class="stat.type"
              @click="handleStatClick(stat.key)"
            >
              <div class="stat-icon">
                <el-icon><component :is="stat.icon" /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stat.value }}</div>
                <div class="stat-label">{{ stat.label }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 快速操作按钮 -->
      <div class="quick-buttons">
        <el-row :gutter="12">
          <el-col :span="8">
            <el-button
              type="primary"
              size="small"
              style="width: 100%"
              @click="handleQuickAction('latest')"
            >
              <el-icon><Clock /></el-icon>
              最新评论
            </el-button>
          </el-col>
          <el-col :span="8">
            <el-button
              type="success"
              size="small"
              style="width: 100%"
              @click="handleQuickAction('popular')"
            >
              <el-icon><Star /></el-icon>
              热门评论
            </el-button>
          </el-col>
          <el-col :span="8">
            <el-button
              type="warning"
              size="small"
              style="width: 100%"
              @click="handleQuickAction('sensitive')"
            >
              <el-icon><Warning /></el-icon>
              敏感评论
            </el-button>
          </el-col>
        </el-row>

        <el-row :gutter="12" style="margin-top: 12px">
          <el-col :span="8">
            <el-button
              type="info"
              size="small"
              style="width: 100%"
              @click="handleQuickAction('today')"
            >
              <el-icon><DocumentChecked /></el-icon>
              今日评论
            </el-button>
          </el-col>
          <el-col :span="8">
            <el-button
              type="danger"
              size="small"
              style="width: 100%"
              @click="handleQuickAction('deleted')"
            >
              <el-icon><Delete /></el-icon>
              已删除
            </el-button>
          </el-col>
          <el-col :span="8">
            <el-button
              size="small"
              style="width: 100%"
              @click="handleQuickAction('all')"
            >
              <el-icon><List /></el-icon>
              全部评论
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 快速筛选 -->
      <div class="quick-filters">
        <el-divider content-position="left">快速筛选</el-divider>
        <div class="filter-row">
          <span class="filter-label">时间范围：</span>
          <el-button-group size="small">
            <el-button
              :type="timeFilter === 'today' ? 'primary' : ''"
              @click="handleTimeFilter('today')"
            >
              今天
            </el-button>
            <el-button
              :type="timeFilter === 'week' ? 'primary' : ''"
              @click="handleTimeFilter('week')"
            >
              本周
            </el-button>
            <el-button
              :type="timeFilter === 'month' ? 'primary' : ''"
              @click="handleTimeFilter('month')"
            >
              本月
            </el-button>
            <el-button
              :type="timeFilter === 'all' ? 'primary' : ''"
              @click="handleTimeFilter('all')"
            >
              全部
            </el-button>
          </el-button-group>
        </div>

        <div class="filter-row">
          <span class="filter-label">评论状态：</span>
          <el-button-group size="small">
            <el-button
              :type="statusFilter === null ? 'primary' : ''"
              @click="handleStatusFilter(null)"
            >
              全部
            </el-button>
            <el-button
              :type="statusFilter === 1 ? 'primary' : ''"
              @click="handleStatusFilter(1)"
            >
              正常显示
            </el-button>
            <el-button
              :type="statusFilter === 0 ? 'primary' : ''"
              @click="handleStatusFilter(0)"
            >
              已删除
            </el-button>
          </el-button-group>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  Refresh,
  Clock,
  Star,
  Warning,
  DocumentChecked,
  Delete,
  List,
  ChatDotRound,
  Select
} from "@element-plus/icons-vue";
import {
  getCommentStatisticsApi,
  type CommentListQuery
} from "@/api/comment-management";

// Emits
const emit = defineEmits<{
  quickAction: [action: string, params?: CommentListQuery];
  refresh: [];
}>();

// 响应式数据
const loading = ref(false);
const timeFilter = ref<string>("all");
const statusFilter = ref<number | null>(null);

const statistics = reactive({
  totalComments: 0,
  todayComments: 0,
  sensitiveComments: 0,
  deletedComments: 0
});

// 计算属性
const quickStats = computed(() => [
  {
    key: "total",
    label: "总评论",
    value: statistics.totalComments,
    type: "primary",
    icon: ChatDotRound
  },
  {
    key: "today",
    label: "今日评论",
    value: statistics.todayComments,
    type: "success",
    icon: Clock
  },
  {
    key: "sensitive",
    label: "敏感评论",
    value: statistics.sensitiveComments,
    type: "danger",
    icon: Warning
  },
  {
    key: "deleted",
    label: "已删除",
    value: statistics.deletedComments,
    type: "info",
    icon: Delete
  }
]);

// 方法
const loadStatistics = async () => {
  try {
    loading.value = true;

    // 只需要调用统计API，它已经包含了所有需要的数据
    const statsRes = await getCommentStatisticsApi();

    if (statsRes.code === 200) {
      const data = statsRes.data;
      console.log("快速操作面板 - 统计数据:", data);
      statistics.totalComments = data.totalComments || 0;
      statistics.todayComments = data.todayComments || 0;
      statistics.sensitiveComments = data.sensitiveComments || 0;
      statistics.deletedComments = data.deletedComments || 0;
      console.log("快速操作面板 - 更新后的统计:", {
        totalComments: statistics.totalComments,
        todayComments: statistics.todayComments,
        sensitiveComments: statistics.sensitiveComments,
        deletedComments: statistics.deletedComments
      });
    } else {
      console.error("获取统计数据失败:", statsRes.message);
    }
  } catch (error) {
    console.error("加载统计数据失败:", error);
  } finally {
    loading.value = false;
  }
};

const handleRefresh = () => {
  loadStatistics();
  emit("refresh");
};

const handleStatClick = (statKey: string) => {
  const params: CommentListQuery = { current: 1, size: 20 };

  switch (statKey) {
    case "today":
      // 今日评论 - 可以通过时间范围过滤
      const today = new Date();
      const todayStart = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate()
      );
      const todayEnd = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate(),
        23,
        59,
        59
      );
      params.startTime = todayStart
        .toISOString()
        .slice(0, 19)
        .replace("T", " ");
      params.endTime = todayEnd.toISOString().slice(0, 19).replace("T", " ");
      console.log("统计卡片今日评论时间参数:", {
        startTime: params.startTime,
        endTime: params.endTime
      });
      break;
    case "sensitive":
      params.isSensitive = 1;
      break;
    case "deleted":
      params.status = 0;
      break;
    case "total":
    default:
      // 显示全部评论
      break;
  }

  emit("quickAction", "filter", params);
};

const handleQuickAction = (action: string) => {
  // 对于最新评论和热门评论，发送特殊事件
  if (action === "latest" || action === "popular") {
    emit("quickAction", action);
    return;
  }

  const params: CommentListQuery = {
    current: 1,
    size: 20,
    keyword: "",
    status: undefined,
    isSensitive: undefined,
    articleId: undefined,
    userId: undefined,
    startTime: "",
    endTime: ""
  };

  switch (action) {
    case "today":
      // 今日评论 - 设置今日时间范围
      const today = new Date();
      const todayStart = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate()
      );
      const todayEnd = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate(),
        23,
        59,
        59
      );
      params.startTime = todayStart
        .toISOString()
        .slice(0, 19)
        .replace("T", " ");
      params.endTime = todayEnd.toISOString().slice(0, 19).replace("T", " ");
      console.log("今日评论时间参数:", {
        startTime: params.startTime,
        endTime: params.endTime
      });
      break;
    case "sensitive":
      params.isSensitive = 1;
      break;
    case "pending":
      params.status = 0;
      break;
    case "deleted":
      params.status = 3;
      break;
    case "all":
    default:
      // 显示全部评论 - 使用默认的重置参数
      break;
  }

  emit("quickAction", action, params);
};

const handleTimeFilter = (filter: string) => {
  timeFilter.value = filter;

  const params: CommentListQuery = { current: 1, size: 20 };
  const now = new Date();

  switch (filter) {
    case "today":
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const todayEnd = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate(),
        23,
        59,
        59
      );
      params.startTime = today.toISOString().slice(0, 19).replace("T", " ");
      params.endTime = todayEnd.toISOString().slice(0, 19).replace("T", " ");
      console.log("时间过滤器今日参数:", {
        startTime: params.startTime,
        endTime: params.endTime
      });
      break;
    case "week":
      const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      params.startTime = weekAgo.toISOString().slice(0, 19).replace("T", " ");
      break;
    case "month":
      const monthAgo = new Date(
        now.getFullYear(),
        now.getMonth() - 1,
        now.getDate()
      );
      params.startTime = monthAgo.toISOString().slice(0, 19).replace("T", " ");
      break;
    case "all":
    default:
      // 不设置时间限制
      break;
  }

  if (statusFilter.value !== null) {
    params.status = statusFilter.value;
  }

  emit("quickAction", "timeFilter", params);
};

const handleStatusFilter = (status: number | null) => {
  statusFilter.value = status;

  const params: CommentListQuery = { current: 1, size: 20 };

  if (status !== null) {
    params.status = status;
  }

  // 应用时间筛选
  if (timeFilter.value !== "all") {
    const now = new Date();
    switch (timeFilter.value) {
      case "today":
        const today = new Date(
          now.getFullYear(),
          now.getMonth(),
          now.getDate()
        );
        const todayEnd = new Date(
          now.getFullYear(),
          now.getMonth(),
          now.getDate(),
          23,
          59,
          59
        );
        params.startTime = today.toISOString().slice(0, 19).replace("T", " ");
        params.endTime = todayEnd.toISOString().slice(0, 19).replace("T", " ");
        console.log("状态过滤器今日参数:", {
          startTime: params.startTime,
          endTime: params.endTime
        });
        break;
      case "week":
        const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
        params.startTime = weekAgo.toISOString().slice(0, 19).replace("T", " ");
        break;
      case "month":
        const monthAgo = new Date(
          now.getFullYear(),
          now.getMonth() - 1,
          now.getDate()
        );
        params.startTime = monthAgo
          .toISOString()
          .slice(0, 19)
          .replace("T", " ");
        break;
    }
  }

  emit("quickAction", "statusFilter", params);
};

// 生命周期
onMounted(() => {
  loadStatistics();
});
</script>

<style scoped lang="scss">
.quick-actions-panel {
  margin-bottom: 16px;

  .panel-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .actions-grid {
    .stats-section {
      margin-bottom: 16px;

      .stat-card {
        display: flex;
        align-items: center;
        padding: 12px;
        cursor: pointer;
        border: 1px solid #e4e7ed;
        border-radius: 8px;
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
          transform: translateY(-2px);
        }

        &.primary {
          color: white;
          background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
          border-color: #409eff;
        }

        &.success {
          color: white;
          background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
          border-color: #67c23a;
        }

        &.warning {
          color: white;
          background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
          border-color: #e6a23c;
        }

        &.danger {
          color: white;
          background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
          border-color: #f56c6c;
        }

        .stat-icon {
          margin-right: 12px;
          font-size: 24px;
          opacity: 0.8;
        }

        .stat-content {
          .stat-number {
            font-size: 20px;
            font-weight: bold;
            line-height: 1;
          }

          .stat-label {
            margin-top: 4px;
            font-size: 12px;
            opacity: 0.9;
          }
        }
      }
    }

    .quick-buttons {
      margin-bottom: 16px;
    }

    .quick-filters {
      .filter-row {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        .filter-label {
          min-width: 80px;
          margin-right: 12px;
          font-size: 14px;
          color: #606266;
        }
      }
    }
  }
}
</style>
